package com.aaa.service.impl;

import com.aaa.dao.UserDao;
import com.aaa.entity.UserInfo;
import com.aaa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;
    @Autowired
    PasswordEncoder pe; //注入密码编译类实例
    @Bean   // 这个方法注入也可以放到@Configuration类中
    public UserDetailsService userDetailsService() {
        return new UserDetailsService() {    // 接口实现类
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                UserInfo userInfo= userDao.login(username); // 根据用户名查找用户的信息  username
                //System.out.println(userInfo);
                if(userInfo==null){  // 如果失败抛出异常
                    throw new UsernameNotFoundException(username);
                }else{
                    List<SimpleGrantedAuthority> authorities=new ArrayList<>();  // 创建一个空的权限集合
                    authorities.add(new SimpleGrantedAuthority("admin"));     // 随便加一个授权,应该从数据库中获取
                    return new User(username,userInfo.getPassword(),authorities);

                }  // 返回一个UserDetails对象
            }
        };
    }


    @Override
    public int userAdd(UserInfo userInfo) {
        String pass=pe.encode(userInfo.getPassword());//对密码进行加密重新编码
        userInfo.setPassword(pass);
        return userDao.userAdd(userInfo);
    }

    @Override
    public int checkUserRepeat(String username) {
        return userDao.checkUserRepeat(username);
    }
}
